package com.wzh.navcode.strategy;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wzh.navcode.domain.entity.HotData;
import com.wzh.navcode.domain.vo.ZhiHuHotTopic;
import com.wzh.navcode.service.CrawlStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangzhenghai
 * description: 知乎策略
 */
@Service("zhihuStrategy")
@Slf4j
public class ZhihuCrawlStrategy implements CrawlStrategy {
    private static final String ZHIHU_URL = "https://api.it8.com.cn/zhihu";

    @Override
    public List<HotData> crawl() {
        List<HotData> hotDataList = new ArrayList<>();
        try {
            String res = HttpUtil.get(ZHIHU_URL);
            Object o = JSONUtil.parseObj(res).get("data");
            List<ZhiHuHotTopic> list = JSONUtil.parseArray(o).toList(ZhiHuHotTopic.class);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            String formattedTime = LocalDateTime.now().format(formatter);
            for (ZhiHuHotTopic hotTopic : list) {
                hotDataList.add(
                        HotData.builder()
                                .title(hotTopic.getTitle())
                                .url(hotTopic.getUrl())
                                .hotValue(hotTopic.getHot()!=null ? String.format("%.1f万", hotTopic.getHot() / 10000.0):"↑")
                                .crawlTime("今天" + formattedTime)
                                .platform("知乎")
                                .build());
            }
        } catch (Exception e) {
            log.error("知乎爬取失败", e);
        }
        return hotDataList;
    }
}